#include <jni.h>
#include <android/log.h>
#include <android/native_window_jni.h>
#include <android/trace.h>
#include "native_camera_manager.h"

// 全局相机管理器实例
static NativeCameraManager* g_cameraManager = nullptr;

extern "C" {

/**
 * 初始化相机系统
 * @param env JNI环境
 * @param thiz Java对象实例
 * @return 初始化是否成功
 */
JNIEXPORT jboolean JNICALL
Java_com_example_nativecamera_MainActivity_nativeInitCamera(JNIEnv *env, jobject thiz) {
    // 标记未使用的参数以避免编译警告
    (void)env;
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeInitCamera");
    
    if (!g_cameraManager) {
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Creating new camera manager");
        g_cameraManager = new NativeCameraManager();
    } else {
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Camera manager already exists");
    }
    
    bool result = g_cameraManager->initialize();
    if (result) {
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "JNI: Camera initialization successful");
    } else {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Camera initialization failed");
    }
    
    ATrace_endSection();
    return result;
}

/**
 * 获取可用相机列表
 * @param env JNI环境
 * @param thiz Java对象实例
 * @return 相机ID字符串数组
 */
JNIEXPORT jobjectArray JNICALL
Java_com_example_nativecamera_MainActivity_nativeGetAvailableCameras(JNIEnv *env, jobject thiz) {
    // 标记未使用的参数以避免编译警告
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeGetAvailableCameras");
    
    if (!g_cameraManager) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Camera manager is null");
        ATrace_endSection();
        return nullptr;
    }
    
    ATrace_beginSection("GET_CAMERAS");
    std::vector<std::string> cameras = g_cameraManager->getAvailableCameras();
    ATrace_endSection();
    
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Found %zu cameras", cameras.size());
    
    // 创建Java字符串数组
    jclass stringClass = env->FindClass("java/lang/String");
    if (!stringClass) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to find String class");
        ATrace_endSection();
        return nullptr;
    }
    
    jobjectArray result = env->NewObjectArray(cameras.size(), stringClass, nullptr);
    if (!result) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to create object array");
        ATrace_endSection();
        return nullptr;
    }
    
    ATrace_beginSection("POPULATE_CAMERA_ARRAY");
    for (size_t i = 0; i < cameras.size(); i++) {
        jstring cameraId = env->NewStringUTF(cameras[i].c_str());
        env->SetObjectArrayElement(result, i, cameraId);
        env->DeleteLocalRef(cameraId);
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Added camera %s to array", cameras[i].c_str());
    }
    ATrace_endSection();
    
    ATrace_endSection();
    return result;
}

/**
 * 打开指定相机
 * @param env JNI环境
 * @param thiz Java对象实例
 * @param cameraId 相机ID
 * @return 打开是否成功
 */
JNIEXPORT jboolean JNICALL
Java_com_example_nativecamera_MainActivity_nativeOpenCamera(JNIEnv *env, jobject thiz, jstring cameraId) {
    // 标记未使用的参数以避免编译警告
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeOpenCamera");
    
    if (!g_cameraManager) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Camera manager is null");
        ATrace_endSection();
        return false;
    }
    
    const char* cameraIdStr = env->GetStringUTFChars(cameraId, nullptr);
    if (!cameraIdStr) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to convert camera ID string");
        ATrace_endSection();
        return false;
    }
    
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Opening camera %s", cameraIdStr);
    
    bool result = g_cameraManager->openCamera(std::string(cameraIdStr));
    env->ReleaseStringUTFChars(cameraId, cameraIdStr);
    
    if (result) {
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "JNI: Camera opened successfully");
    } else {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to open camera");
    }
    
    ATrace_endSection();
    return result;
}

/**
 * 关闭相机
 * @param env JNI环境
 * @param thiz Java对象实例
 */
JNIEXPORT void JNICALL
Java_com_example_nativecamera_MainActivity_nativeCloseCamera(JNIEnv *env, jobject thiz) {
    // 标记未使用的参数以避免编译警告
    (void)env;
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeCloseCamera");
    
    if (g_cameraManager) {
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Closing camera");
        g_cameraManager->closeCamera();
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "JNI: Camera closed successfully");
    } else {
        __android_log_print(ANDROID_LOG_WARN, "NativeCamera", "JNI: No camera manager to close");
    }
    
    ATrace_endSection();
}

/**
 * 开始预览
 * @param env JNI环境
 * @param thiz Java对象实例
 * @param surface Java Surface对象
 * @return 预览开始是否成功
 */
JNIEXPORT jboolean JNICALL
Java_com_example_nativecamera_MainActivity_nativeStartPreview(JNIEnv *env, jobject thiz, jobject surface) {
    // 标记未使用的参数以避免编译警告
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeStartPreview");
    
    if (!g_cameraManager) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Camera manager is null");
        ATrace_endSection();
        return false;
    }
    
    if (!surface) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Surface is null");
        ATrace_endSection();
        return false;
    }
    
    // 从Java Surface获取ANativeWindow
    ATrace_beginSection("GET_NATIVE_WINDOW");
    ANativeWindow* window = ANativeWindow_fromSurface(env, surface);
    if (!window) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to get native window from surface");
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Starting preview");
    
    bool result = g_cameraManager->startPreview(window);
    
    if (result) {
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "JNI: Preview started successfully");
    } else {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to start preview");
        // 如果预览失败，释放窗口资源
        ANativeWindow_release(window);
    }
    
    ATrace_endSection();
    return result;
}

/**
 * 停止预览
 * @param env JNI环境
 * @param thiz Java对象实例
 */
JNIEXPORT void JNICALL
Java_com_example_nativecamera_MainActivity_nativeStopPreview(JNIEnv *env, jobject thiz) {
    // 标记未使用的参数以避免编译警告
    (void)env;
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeStopPreview");
    
    if (g_cameraManager) {
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Stopping preview");
        g_cameraManager->stopPreview();
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "JNI: Preview stopped successfully");
    } else {
        __android_log_print(ANDROID_LOG_WARN, "NativeCamera", "JNI: No camera manager to stop preview");
    }
    
    ATrace_endSection();
}

/**
 * 拍照
 * @param env JNI环境
 * @param thiz Java对象实例
 * @param filename 保存文件名
 * @return 拍照是否成功
 */
JNIEXPORT jboolean JNICALL
Java_com_example_nativecamera_MainActivity_nativeTakePicture(JNIEnv *env, jobject thiz, jstring filename) {
    // 标记未使用的参数以避免编译警告
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeTakePicture");
    
    if (!g_cameraManager) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Camera manager is null");
        ATrace_endSection();
        return false;
    }
    
    const char* filenameStr = env->GetStringUTFChars(filename, nullptr);
    if (!filenameStr) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to convert filename string");
        ATrace_endSection();
        return false;
    }
    
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Taking picture with filename: %s", filenameStr);
    
    bool result = g_cameraManager->takePicture(std::string(filenameStr));
    env->ReleaseStringUTFChars(filename, filenameStr);
    
    if (result) {
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "JNI: Picture taken successfully");
    } else {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "JNI: Failed to take picture");
    }
    
    ATrace_endSection();
    return result;
}

/**
 * 检查相机是否已打开
 * @param env JNI环境
 * @param thiz Java对象实例
 * @return 相机是否已打开
 */
JNIEXPORT jboolean JNICALL
Java_com_example_nativecamera_MainActivity_nativeIsCameraOpen(JNIEnv *env, jobject thiz) {
    // 标记未使用的参数以避免编译警告
    (void)env;
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeIsCameraOpen");
    
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Checking if camera is open");
    
    if (!g_cameraManager) {
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Camera manager not initialized");
        ATrace_endSection();
        return false;
    }
    
    bool isOpen = g_cameraManager->isCameraOpen();
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Camera open status: %s", isOpen ? "true" : "false");
    
    ATrace_endSection();
    return isOpen;
}

/**
 * 清理相机资源
 * @param env JNI环境
 * @param thiz Java对象实例
 */
JNIEXPORT void JNICALL
Java_com_example_nativecamera_MainActivity_nativeCleanup(JNIEnv *env, jobject thiz) {
    // 标记未使用的参数以避免编译警告
    (void)env;
    (void)thiz;
    
    ATrace_beginSection("Java_com_example_nativecamera_MainActivity_nativeCleanup");
    
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "JNI: Cleaning up camera resources");
    
    if (g_cameraManager) {
        delete g_cameraManager;
        g_cameraManager = nullptr;
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "JNI: Camera manager cleaned up");
    }
    
    ATrace_endSection();
}

} // extern "C"